package com.nextbusmn.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 *  A source object from which to read the schedule data.
 *  @author Trent Olson
 */
public class ScheduleSource {

	private URL url;
	private boolean priv;
	
	public ScheduleSource(String sourceURL, boolean privileged) {
		try {
			url = new URL(sourceURL);
			priv = privileged;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
  /**
   * Get the stream from which to read the schedule.
   */
	public InputStream getScheduleStream() throws IOException {		
		InputStream in = null;
    // if we need elevated privileges to read the stream, 
    // wrap in a PrivilegedAction
		if (priv) {
			in = AccessController.doPrivileged(
				new PrivilegedAction<InputStream>() {
					public InputStream run() {
						return getStream(url);
					}
				}
			);
    // otherwise, just get the stream 
		} else {
			in = getStream(url);
		}
		if (in == null) {
			throw new IOException("No connection!");
		}
		return in;
	}
	
  /**
   * Helper method to get the stream from the URL
   */
	private InputStream getStream(URL url) {
		URLConnection connection = null;
		try {
			connection = url.openConnection();
      // Google App Engine will only allow a 60 second connection,
      // So set the connection timeout to 5 secs. 
			connection.setConnectTimeout(5000);
      // and the read timeout to 55 secs.
			connection.setReadTimeout(55000);
			connection.connect();
			return connection.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
